<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/6 0006
 * Time: 16:33
 */
namespace app\http;
use think\worker\Server;
class Worker extends Server
{
     protected $protocol = 'websocket';
    protected $host     = '0.0.0.0';
    protected $port     = '2346';
    //创建两个接收的端口，一个接收html数据，一个接收php内部发送的数据
     public function onWorkerStart($worker){
         //创建端口
         $obj = new \Workerman\Worker('tcp://0.0.0.0:4646');
         $obj->onMessage = function ($connections,$datas){
             //内部端口获取了数据的处理
             print_r($datas);
             $array  = explode(',',$datas);
             $arrays = [];
//             print_r($array);
             foreach ($array as $key=>$value){
                 $arrayb = explode(':',$value);
//                 print_r($arrayb);
                 $arrays[$arrayb[0]] = $arrayb[1];
             }
//             print_r($arrays);
             $obs = $this->worker->connections;
             if(isset($obs[$arrays['to']])){
                 //如果这个链接存在，就发送数据
                 $obs[$arrays['to']]->send(json_encode(['data'=>$arrays['data']]));
             }
         };
         $obj->listen();
     }
     //接收html发送的数据处理
    public function onMessage($connection,$data)
    {
//        echo $data;
        $array = json_decode($data,true);
        if(isset($array['name'])){
            //将当前链接的user保存起来
            $this->worker->connections[$array['name']]=$connection;
        }else{
            $quan = $this->worker->connections;
            $quan[$array['to']]->send(json_encode(['data'=>$array['data']]));
        }
    }
}